<?php

namespace Controller;

use Lib\Util\Util,
    Lib\Request,
    Lib\Util\Session,
    Lib\Util\Cache;

class AdminBackground extends Admin {

    private $imageExtensions = array('png', 'bmp', 'jpg', 'jpeg', 'gif');

    public function index() {
        $this->set('images', App::bodyBackgrounds());

        $maxUpload = ini_get('upload_max_filesize');
        $maxPost   = ini_get('post_max_size');
        if (Util::parseFileSize($maxUpload) < Util::parseFileSize($maxPost)) {
            $maxUpload = $maxPost;
        }
        $this->set('maxSize', $maxUpload);
    }

    public function save() {
        $image = Request::file('image');
        if (! empty($image)) {
            $filename = urldecode($image['name']);
            $tmpName  = $image['tmp_name'];
            $error    = $image['error'];

            $ext      = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
            
            if (in_array($ext, $this->imageExtensions)) {
                if (! $error) {
                    $destination = $this->getDestinationPath($filename);
                    if (move_uploaded_file($tmpName, $destination)) {
                        Session::flash(MESSAGE_IMAGE_SENT, 'ok');
                    } else {
                        Session::flash(ERROR_UPLOADING_FILE, 'error');
                    }
                } else {
                    Session::flash(ERROR_UPLOADING_FILE, 'error');
                }
            } else {
                Session::flash(ERROR_INVALID_IMAGE, 'error');
            }
        }
        $this->redirect('index');
    }

    public function delete($file) {
        $path = $this->getDestinationPath($file);
        if (is_file($path)) {
            $this->deleteCacheImage($file);
            if (@unlink($path)) {
                Session::flash(sprintf(MESSAGE_IMAGE_DELETED, $file), 'ok');
            } else {
                Session::flash(ERROR_DELETING_IMAGE, 'error');
            }
        }
        
        $this->redirect('index');
    }

    public function delete_cache($image) {
        if ($this->deleteCacheImage($image)) {
            Session::flash(sprintf(MESSAGE_CACHE_IMAGES_DELETED, $image), 'ok');
        } else {
            Session::flash(ERROR_DELETING_CACHE_IMAGES, 'error');
        }
        $this->redirect('index');
    }

    private function getDestinationPath($filename = null) {
        return DIR_IMG . DS . 'background' . DS . $filename;
    }

    private function deleteCacheImage($image) {
        return Cache::delete('images' . DS . 'background' . DS . $image);
    }

}